package com.young.weixin.web;

import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.young.common.util.CommonUtil;
import com.young.common.util.StringUtils;
import com.young.weixin.model.WxMessageRequest;
import com.young.weixin.service.IWxBaseService;
import com.young.weixin.service.IWxMessageService;
import com.young.weixin.util.WxUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 对接微信的接口
 *
 * @author wangjiyu@imdada.cn
 * @create 2019/5/5
 */
@Controller
@RequestMapping("/weixin/api")
public class WxApiController {

    private static final Logger logger = LoggerFactory.getLogger(WxApiController.class);

    /**
     * 微信基础服务
     */
    @Autowired
    private IWxBaseService wxBaseService;
    /**
     * 微信消息服务
     */
    @Autowired
    private IWxMessageService wxMessageService;

    /**
     * 微信API - 服务器校验
     * 微信用来验证公众号的服务器配置是否正确, 通过发起get请求的方式测试我们的服务能否正确应答
     *
     * @param app
     * @param request
     * @return
     */
    @RequestMapping(value = "/{app}/message", method = RequestMethod.GET)
    @ResponseBody
    public Object message4Get(@PathVariable("app") String app, WxMessageRequest wxMessageRequest, HttpServletRequest request) {
        logger.info("[微信API-服务器校验] 接收到微信公众号应用[{}]的消息,消息内容={}", app, wxMessageRequest);
        if (!this.checkParamForGet(wxMessageRequest)) {
            logger.error("[微信API-服务器校验] 参数校验失败,应用={},入参={}", app, wxMessageRequest);
            return "param error";
        }
        return wxBaseService.serverCheck(wxMessageRequest);
    }

    /**
     * 接收消息
     *
     * @param app
     * @param wxMessageRequest
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/{app}/message", method = RequestMethod.POST)
    public void message4Post(@PathVariable("app") String app, WxMessageRequest wxMessageRequest, HttpServletRequest request, HttpServletResponse response) {
        PrintWriter pw = null;
        try {
            logger.info("[微信API-接收消息] 接收到微信公众号应用[{}]的消息,消息内容={}", app, wxMessageRequest);

            // 读取body体的数据
            String xml = WxUtil.readBody(request.getInputStream());
            logger.debug("[微信API-接收消息] body数据=={}", xml);

            // 消息处理
            String res = wxMessageService.handleWxMessage(app, wxMessageRequest, xml);

            // 写入响应
            response.setCharacterEncoding("utf8");
            pw = response.getWriter();
            pw.write(res);
        } catch (Throwable e) {
            logger.error("[微信API-接收消息] 发生异常,app={},入参={}", app, wxMessageRequest, e);
        } finally {
            if (pw != null) {
                pw.flush();
                pw.close();
            }
        }

    }

    /**
     * 校验参数
     *
     * @param weixinMessageRequest
     * @return
     */
    private boolean checkParamForGet(WxMessageRequest weixinMessageRequest) {
        if (weixinMessageRequest == null || StringUtils.isBlank(weixinMessageRequest.getSignature()) || StringUtils.isBlank(weixinMessageRequest.getTimestamp())
                || StringUtils.isBlank(weixinMessageRequest.getNonce()) || StringUtils.isBlank(weixinMessageRequest.getEchostr())) {
            return false;
        }
        return true;
    }

}
